// const { exec } = require('child_process');

// const fileUrl = 'https://ssscdn.io/ssstwitter/aHR0cHM6Ly92aWRlby50d2ltZy5jb20vYW1wbGlmeV92aWRlby8xNzY3NDgyNDEyMTg1ODk0OTEzL3ZpZC9hdmMxLzcyMHgxMjgwL2dreWJMNlVmZm9MMWpuNWMubXA0P3RhZz0xNA=='; // 替换为要下载的文件 URL
// const downloadPath = '/root/' + Date.now() + ".mp4"; // 替换为要保存的文件路径

// const wgetCmd = `wget --progress=bar:force:noscroll -O "${downloadPath}" "${fileUrl}"`;

// const downloadFileWithProgress = () => {
//     const child = exec(wgetCmd);

//     // 监听子进程的输出
//     child.stderr.on('data', (data) => {
//         const output = data.toString();
//         const progressMatch = output.match(/\d+(\.\d+)?%/);

//         if (progressMatch) {
//             const progress = progressMatch[0];
//             console.log(`Downloading: ${progress}`);
//         }
//     });

//     child.on('close', (code) => {
//         if (code === 0) {
//             console.log('Download completed!');
//         } else {
//             console.log(`Download failed with code ${code}`);
//         }
//     });
// };

// downloadFileWithProgress();
// import { createServer } from "http";
const fs = require('fs');
const { createServer } = require('http');
const { Server } = require('socket.io');
const httpServer = createServer();
const io = new Server(httpServer, {
    cors: {
        origin: "http://192.168.150.108:8000"
    }
});

io.on("connection", (socket) => {
    socket.emit("msg", "hello", (response) => {
        console.log(response); // "got it"  
        // socket.disconnect(true);   
    });

    socket.on("disconnect", (reason) => {
        console.log("client 斷開", reason);
    });

    socket.on('file', (data) => {
        // socket.broadcast.emit("b2c-file", data);//除了自己，其他人全部發送
        io.sockets.emit("b2c-file", data);//全部人都發送
        // const fileStream = fs.createReadStream(data.path);
        // const buffer = Buffer.from(data.buffer);
        // const fileStream = new fs.ReadStream(buffer);

        // fileStream.on('data', (chunk) => {
        //     socket.emit('fileChunk', chunk);
        // });

        // fileStream.on('end', () => {
        //     socket.emit('fileEnd');
        // });
    });
});

io.on("disconnect", (reason) => {
    console.log("斷開", reason); // the client may or may not receive it
});

httpServer.listen(3000);
console.log('socket serve 3000');
